<template>
  <el-container id="menus">
    <el-header id="elheader" class="header" height="auto">
      <el-form :label-position="labelPosition" :model="formLabelAlign" class="FormInput">
        <el-button v-if="buttonPermission.add.buttonCaption" type="primary" @click="OnBtnAdd(1)">{{ buttonPermission.add.buttonCaption }}
        </el-button>
      </el-form>
    </el-header>
    <el-main :height="mainHeight">
      <el-table ref="table" :height="tableHeight" :data="tableData" style="width: 99.9%" row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border @expand-change="expandChange">
        <el-table-column prop="menuName" label="菜单名称" width="250" />
        <el-table-column prop="menuPath" label="菜单路径" width="250" class="ellipsis" />
        <el-table-column prop="menuAnotherName" label="菜单别名" />
        <el-table-column v-if="false" prop="menuIcon" label="上级菜单" />
        <el-table-column prop="menuIcon" label="菜单图标" width="80">
          <template slot-scope="scope">
            <div>
              <svg-icon class="iconSty" :icon-class="scope.row.menuIcon" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="menuDesc" label="菜单说明" width="250">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <div size="medium" class="ellipsis">{{ scope.row.menuDesc }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="seq" label="排序" width="60" />
        <el-table-column prop="isMenu" label="是否菜单" width="80">
          <template slot-scope="scope">{{ scope.row.isMenu == true ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column prop="status" label="启用状态" width="80">
          <template slot-scope="scope">{{ scope.row.status == true ? '启用' : '禁用' }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="140">
          <template slot-scope="scope">
            <div>{{ scope.row.createTime | formatTDate }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="false" prop="createId" label="创建人ID" />
        <el-table-column label="操作" fixed="right" width="250">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" content="添加下级" placement="top-start" :open-delay="200">
              <el-button v-if="buttonPermission.addchild" circle icon="el-icon-circle-plus-outline" type="primary"
                @click="OnBtnAdd(2, scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="编辑" placement="top-start" :open-delay="200">
              <el-button v-if="buttonPermission.edit.buttonCaption" circle icon="el-icon-edit" type="success"
                @click="handleEdit(scope.$index, scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="删除" placement="top-start" :open-delay="200">
              <el-button v-if="buttonPermission.delete.buttonCaption" circle icon="el-icon-delete" type="danger"
                @click="handleDelete(scope.$index, scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="上移" placement="top-start" :open-delay="200">
              <el-button v-if="buttonPermission.moveup.buttonCaption" circle icon="el-icon-top" type="primary"
                @click="movePostion(scope.row, 0)" />
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="下移" placement="top-start" :open-delay="200">
              <el-button v-if="buttonPermission.movedown.buttonCaption" circle icon="el-icon-bottom" type="primary"
                @click="movePostion(scope.row, 1)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <IconsEdit ref="IconsEdit" @doSelect="doIcoSelect" />
    </el-main>
    <el-dialog title="编辑菜单信息" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false" :center="true">
      <el-form ref="formData" :model="formData" label-width="100px" :rules="formRules">
        <el-form-item label="菜单名称：" prop="menuName" :hide-required-asterisk="false">
          <el-input v-model="formData.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="是否菜单：">
          <el-switch v-model="formData.isMenu" active-text="是" inactive-text="否" @change="isMenuDo" />
        </el-form-item>
        <el-form-item v-if="formData.isMenu" label="菜单路径：" prop="menuPath" :hide-required-asterisk="true">
          <el-input v-model="formData.menuPath" placeholder="请输入菜单路径" />
        </el-form-item>
        <!-- <el-form-item label="菜单别名：" prop="menuAnotherName">
          <el-input v-model="formData.menuAnotherName" placeholder="请输入菜单别名" />
        </el-form-item> -->
        <el-form-item label="组件名称：">
          <el-input v-model="formData.vueName" placeholder="请输入组件名称" />
        </el-form-item>
        <el-form-item label="上级菜单：">
          <el-cascader v-model="parentMenu" style="width:100%" :options="tableData_"
            :props="{ checkStrictly: true, value: 'id', label: 'menuName' }" clearable />
        </el-form-item>
        <el-form-item label="图标">
          <el-tag @click="selectIco">选择</el-tag>
          <svg-icon v-if="iconState == 1" class="iconSty" :icon-class="this.formData.menuIcon" />
        </el-form-item>
        <el-form-item label="排序：" prop="seq">
          <el-input v-model="formData.seq" placeholder="请输入排序数字" />
        </el-form-item>
        <el-form-item label="启用状态：">
          <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="功能按钮">
          <el-select v-model="formData.buttons" multiple placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in buttonOptions" :key="item.id" :label="item.buttonCaption" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单说明：">
          <el-input v-model="formData.menuDesc" type="textarea" :rows="4" :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入菜单说明" />
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="OnBtnClose">关闭</el-button>
        <el-button type="primary" @click="OnBtnSaveSubmit">保存</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
import RequestObject from '@/utils/requestObject'
import request from '@/utils/request'
import height from '@/utils/height'
import { deepClone } from '@/utils/deepClone'
import IconsEdit from '@/components/IconsEdit'
import { getBtnCtr } from '@/utils/BtnControl'
import { setTimeout } from 'timers'

export default {
  name: "PlatformMenu",
  components: {
    IconsEdit
  },
  filters: {
    formatTDate: value => {
      const d = value.split('T')
      return `${d[0]} ${d[1]}`
    }
  },
  data() {
    var checkAppClassId = (rule, value, callback) => {
      if (!this.formData.appClassId || this.formData.appClassId.length < 1) {
        callback(new Error('请选择应用名称'))
      } else {
        callback()
      }
    }
    var checkAge = (rule, value, callback) => {
      if (!value && this.formData.isMenu) {
        return callback(new Error('路径不能为空'))
      } else {
        callback()
      }
    }
    return {
      buttonPermission: {},
      headerHeight: '180px',
      mainHeight: '',
      footerHeight: '50px',
      tableHeight: '500',
      labelPosition: 'right',
      formLabelAlign: {
        name: ''
      },
      tableData: [], // table数据模型
      tableData_: [],
      dialogVisible: false, // 编辑窗口是否显示
      appTrees: [], // 应用树
      formData: {
        // 编辑窗口模型
        id: 0,
        appClassId: [],
        menuName: '',
        menuPath: '',
        menuAnotherName: '',
        status: true,
        menuIcon: '',
        menuDesc: '',
        createTime: new Date(),
        createId: 0,
        seq: 1, // integer($int32)排序(大于一的数字)
        isMenu: false, // 是否菜单
        parentID: -1,
        vueName: '',
        buttons:[]
      },
      formRules: {
        // 数据验证模型
        appClassId: [{ validator: checkAppClassId, trigger: 'blur' }],
        menuName: [
          {
            required: true,
            message: '请输入菜单名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 12,
            message: '菜单名称长度范围在1到12个字符',
            trigger: 'blur'
          }
        ],
        menuAnotherName: [
          {
            min: 1,
            max: 12,
            message: '菜单名称长度范围在1到12个字符',
            trigger: 'blur'
          }
        ],
        menuPath: [
          { validator: checkAge, trigger: 'blur' },
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ]
        // seq:[{ type:'number', required: true, message: '必须为数字值',trigger: 'blur'}]
      },
      pageSize: 25, // 分页显示记录条数
      totalCount: 0, // 总记录数
      pageIndex: 1, // 页码
      sortColumn: '', // 排序字段
      sortOrder: '', // 排序规则
      menuName: '', // 菜单名称查询条件
      menuStatus: '全部', // 菜单状态
      appValue: [], // 查询条件应用名称
      editSelectAppId: [], // 编辑界面选择的APP
      tableSleArr: [],
      parentMenu: [], // 上级菜单
      iconState: 0,
      expandRowKeys: [],
      buttonOptions:[]
    }
  },
  watch: {
    tableData() {
      if (this.pageIndex > 1 && this.tableData.length == []) {
        this.pageIndex--
        // 初始化表格数据
        this.handleQuery()
      }
    },
    dialogVisible(val) {
      if (!val) {
        this.$refs.formData.resetFields()
      }
    }
  },
  created() {
    // 动态头部按钮
    this.buttonPermission = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
    this.mainHeight =
      (
        height -
        126 -
        parseInt(this.headerHeight) -
        parseInt(this.footerHeight)
      ).toString() + 'px'
    this.getTree();
    this.GetButtons();
  },
  mounted() {
    var b = document.documentElement.clientHeight - 84
    this.$nextTick(() => {
      var o = document.getElementById('elheader')
      var h = o.clientHeight || o.offsetHeight
      this.tableHeight = b - h - 40
    })
  },
  methods: {
    GetButtons() {      
      var queryRequest = RequestObject.CreateGetObject(false,1,1,[],[]);      
      request({
        url: '/api/tbuttons',
        method: 'get',
        params: {
          requestObject: JSON.stringify(queryRequest)
        }
      }).then(res => {
          for(let i=0;i<res.data.length;i++){
            this.buttonOptions.push({
              id:res.data[i].id,
              buttonCaption:res.data[i].buttonCaption
            })
          }
        })
        .catch(() => {
          this.$message('error')
        })
    },
    expandChange(row, expanded) {

    },
    getTree() {
      var robject = RequestObject.CreateGetObject(false, 0, 0, [
        { column: 'ParentID', content: '-1', condition: 0 }
      ])
      request({
        url: '/api/TMenus/GetTree',
        method: 'get',
        params: {
          requestObject: robject
        }
      }).then(res => {
        if (res.code === 0) {
          this.tableData = res.data
        } else {
          this.$confirm(res.info, '错误信息', {
            confirmButtonText: '确定',
            type: 'error',
            showCancelButton: false
          })
        }
      })
    },
    handleQuery() {
      this.getTree()

    },
    OnBtnAdd(state, selectedRow) {
      this.tableData_ = deepClone(this.tableData)
      this.formData.id = 0
      this.formData.appClassId = []
      this.formData.menuName = ''
      this.formData.menuPath = ''
      this.formData.menuAnotherName = ''
      this.formData.status = true
      this.formData.menuIcon = ''
      this.formData.menuDesc = ''
      this.formData.createId = 0
      this.dialogVisible = true
      this.formData.seq = 99
      this.formData.isMenu = false
      this.formData.vueName = '';
      this.parentMenu = []

      if (state == 2) {
        this.parentMenu.push(selectedRow.id)
      }
    },
    handleEdit(index, selectedRow) {
      this.tableData_ = deepClone(this.tableData)
      this.setTreeDefault(this.tableData_, selectedRow.id)

      this.GetAppClassId(this.appTrees, selectedRow.appClassId)
      this.formData.id = selectedRow.id
      this.formData.appClassId = this.editSelectAppId
      this.formData.menuName = selectedRow.menuName
      this.formData.menuPath = selectedRow.menuPath
      this.formData.menuAnotherName = selectedRow.menuAnotherName
      this.formData.status = selectedRow.status
      this.formData.menuIcon = selectedRow.menuIcon
      this.formData.menuDesc = selectedRow.menuDesc
      this.formData.createId = selectedRow.createId
      this.formData.seq = selectedRow.seq
      this.formData.isMenu = selectedRow.isMenu
      this.formData.parentID = selectedRow.parentID
      this.formData.vueName = selectedRow.vueName;
      if(!selectedRow.buttons){
        this.formData.buttons = [];
      }else{
        this.formData.buttons = selectedRow.buttons.split(',').map(Number);
      }
      this.parentMenu = []
      this.parentMenu.push(selectedRow.parentID)
      this.dialogVisible = true
    },
    setTreeDefault(dt, id) {
      for (var i = 0; i < dt.length; i++) {
        if (dt[i].id == id) {
          dt.splice(i, 1)
          return
        }
        if (dt[i].children) {
          this.setTreeDefault(dt[i].children, id)
        }
      }
    },
    handleDelete(index, selectedRow) {
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          setTimeout(() => {
            doDel()
          }, 200)
        })
        .catch(() => { })

      var doDel = () => {
        this.$prompt('请输入密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'password',
          inputPattern: /^.{6,20}$/,
          inputErrorMessage: '密码格式不正确(6-20位数密码)'
        })
          .then(({ value }) => {
            this.formData.id = selectedRow.id
            this.formData.passWord = value
            this.formData.appClassId = this.editSelectAppId
            this.formData.menuName = selectedRow.menuName
            this.formData.menuPath = selectedRow.menuPath
            this.formData.menuAnotherName = selectedRow.menuAnotherName
            this.formData.status = selectedRow.status
            this.formData.menuIcon = selectedRow.menuIcon
            this.formData.menuDesc = selectedRow.menuDesc
            this.formData.createTime = new Date(selectedRow.createTime)
            this.formData.createId = selectedRow.createId
            this.formData.seq = selectedRow.seq
            this.formData.isMenu = selectedRow.isMenu
            this.formData.vueName = selectedRow.vueName;
            var deleteData = RequestObject.CreatePostObject(this.formData)
            request({
              url: '/api/TMenus',
              method: 'delete',
              data: deleteData
            }).then(res => {
              if (res.code == -1) {
                this.$confirm(res.info, '错误信息', {
                  confirmButtonText: '确定',
                  type: 'error',
                  showCancelButton: false
                })
              } else {
                this.$message({
                  message: '删除数据成功',
                  type: 'success'
                })
                this.getTree() // 查询数据
              }
            })
          })
          .catch(() => { })
      }
    },
    OnBtnSaveSubmit() {
      this.$refs.formData.validate(valid => {
        if (!valid) {
          this.$message({
            message: '数据不合法，无法保存',
            type: 'error'
          })
        } else {
          var currData = this.GetPostData()
          var currMethod = 'post'
          if (currData.id !== 0) {
            // 修改
            currMethod = 'put'

            if (currData.id == currData.parentID) {
              this.$message({
                showClose: true,
                message: '父级菜单不能为当前菜单',
                type: 'error'
              })
              return
            }
          }
          var data = RequestObject.CreatePostObject(currData)
          request({
            url: '/api/TMenus',
            method: currMethod,
            data: data
          }).then(res => {
            if (res.code == -1) {
              this.$confirm(res.info, '错误信息', {
                confirmButtonText: '确定',
                type: 'error',
                showCancelButton: false
              })
            } else {
              this.getTree()
              this.$message({
                message: '保存数据成功',
                type: 'success'
              })
              this.dialogVisible = false
            }
          })
        }
      })
    },
    OnBtnClose() {
      this.dialogVisible = false
    },
    GetPostData() {
      var result = {
        id: this.formData.id,
        menuName: this.formData.menuName,
        menuPath: this.formData.menuPath,
        seq: this.formData.seq,
        isMenu: this.formData.isMenu,
        menuAnotherName: this.formData.menuAnotherName,
        status: this.formData.status,
        menuIcon: this.formData.menuIcon,
        menuDesc: this.formData.menuDesc,
        vueName: this.formData.vueName,
        createId: 0,
        }
        if(this.formData.buttons){
          result.buttons = this.formData.buttons.join(',')
        }else{
          result.buttons = ''
        }
      if (this.parentMenu == undefined || this.parentMenu == '') {
        result.parentID = -1
      } else {
        result.parentID = this.parentMenu[this.parentMenu.length - 1]
      }
      console.log('res:',result)
      return result
    },
    handlePaging(index) {
      this.pageIndex = index
      this.handleQuery()
    },
    handelMenuStatusChange() {
      this.handleQuery()
    },
    handelSortChange(currSort) {
      this.sortColumn = currSort.prop
      this.sortOrder = currSort.order == 'ascending' ? 'asc' : 'desc'
      this.handleQuery()
    },
    handelDatePicker() {
      this.handleQuery()
    },
    handelKeyDown() {
      this.handleQuery()
    },
    handleAppChange(value) {
      this.handleQuery()
    },
    GetAppClassId(tree, appId, level) {
      tree.forEach((v, i) => {
        if (v.value == appId) {
          var strAry = level + '' + v.value
          var ary = strAry.split(',')
          var len = ary.length
          var rtn = [ary[0], ary[len - 2], ary[len - 1]]
          this.editSelectAppId = rtn
          return
        } else {
          level = level + '' + v.value + ','
          if (v.children && v.children.length > 0) {
            return this.GetAppClassId(v.children, appId, level)
          }
        }
      })
    },
    isMenuDo(state) {
      // 是否菜单

    },
    selectIco() {
      // 选择图标

      this.$refs.IconsEdit.doOpen()
    },
    doIcoSelect(text, state) {
      this.$refs.IconsEdit.doClose()
      this.formData.menuIcon = text
      this.iconState = state
    },
    movePostion(item, state) {
      var data = RequestObject.CreatePostObject({ id: item.id, type: state })
      request({
        url: '/api/TMenus/MovePostion',
        method: 'put',
        data: data
      }).then(res => {
        if (res.code == -1) {
          this.$confirm(res.info, '错误信息', {
            confirmButtonText: '确定',
            type: 'error',
            showCancelButton: false
          })
        } else {
          this.getTree()
          this.$message({
            message: '保存数据成功',
            type: 'success'
          })
          // this.$refs.formData.resetFields()
          this.dialogVisible = false
          // this.handleQuery() // 查询数据
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
#menus /deep/ {
  .header {
    padding-top: 10px;
  }

  .el-tag {
    cursor: pointer;
  }

  .ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
    width: 100%;
    cursor: pointer;
  }

  .iconSty {
    width: 20px;
    height: 20px;
    vertical-align: middle;
  }

  .textCenter {
    text-align: center;
  }

  .dialog-footer {
    text-align: right;
  }
}
</style>
